﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Minio;
using Minio.DataModel.Args;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace ins
{
    public partial class Form1 : Form
    {
        private MinioClient minioClient;

        public Form1()
        {
            InitializeComponent();

            //progressBar1.Maximum = 100;

            // 初始化 Minio 客户端
            string endpoint = "139.196.170.188:9000"; // MinIO 服务地址
            string accessKey = "kecheng"; // MinIO 访问密钥
            string secretKey = "lkclkclkc"; // MinIO 秘密密钥

            //FTP相关配置信息
            string ftpServer = "ftp://139.196.170.188/";
            string ftpUsername = "kecheng";
            string ftpPassword = "lkczy22125@";
            //string filePath = @"D:\software\WebStorm-2021.1.3.exe"; // 本地文件路径
            //string remoteFilePath = "WebStorm-2021.1.3.exe"; // 远程服务器路径



            minioClient = (MinioClient)
                new MinioClient()
                    .WithEndpoint(endpoint)
                    .WithCredentials(accessKey, secretKey)
                    .Build();

            // 动态添加选项
            comboBox1.Items.Add("Redis");
            comboBox1.Items.Add("MySQL");
            comboBox1.Items.Add("Nginx");
            comboBox1.Items.Add("JDK 8");
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string deployOption = comboBox1.SelectedItem.ToString();
                if (string.IsNullOrEmpty(deployOption))
                {
                    MessageBox.Show("请选择部署选项！");
                    return;
                }
                Log("开始部署...");

                string deployPath = Path.Combine(@"D:\modsoft");

                Directory.CreateDirectory(deployPath);

                if (deployOption == "Redis")
                {
                    Log("开始部署 Redis...");
                    await DownloadFileFromMinio("Redis.zip", Path.Combine(deployPath, "redis.zip"));
                    string redisExtractPath = Path.Combine(deployPath, "Redis");
                    ExtractFile(Path.Combine(deployPath, "redis.zip"), redisExtractPath);
                    string actualNginxFolder = Directory.GetDirectories(redisExtractPath)[0];

                    // 启动 Redis
                    StartProcess(Path.Combine(actualNginxFolder, "redis-server.exe"), "");
                    Log("Redis 部署成功！");
                }
                if (deployOption == "Nginx")
                {
                    Log("开始部署 Nginx...");
                    await DownloadFileFromMinio("Nginx.zip", Path.Combine(deployPath, "nginx.zip"));

                    string nginxExtractPath = Path.Combine(deployPath, "Nginx");
                    ExtractFile(Path.Combine(deployPath, "nginx.zip"), nginxExtractPath);

                    string actualNginxFolder = Directory.GetDirectories(nginxExtractPath)[0];

                    // 启动 Nginx
                    StartProcess(Path.Combine(actualNginxFolder, "nginx.exe"), "");
                    Log("Nginx 部署成功！");
                }
                #region jdk远程下载
                //if (deployOption == "JDK 8")
                //{
                //    Log("开始部署 JDK 8...");
                //    await DownloadFileFromMinio("JDK1.8.zip", Path.Combine(deployPath, "jdk8.zip"));
                //    string jdkExtractPath = Path.Combine(deployPath, "JDK8");
                //    ExtractFile(Path.Combine(deployPath, "jdk8.zip"), jdkExtractPath);
                //    string actualJdkFolder = Directory.GetDirectories(jdkExtractPath)[0];
                //    //配置环境变量
                //    ConfigureEnvironmentVariables(actualJdkFolder);
                //}
                #endregion

                if (deployOption == "JDK 8")
                {
                    Log("开始部署 JDK 8...");
                    // 获取项目根目录路径，注意这适用于运行时
                    string projectFolder2 = Path.GetFullPath(
                        Path.Combine(AppDomain.CurrentDomain.BaseDirectory)
                    ); // 获取根目录路径

                    // 组合安装包的完整路径
                    string jdkInstallerPath = Path.Combine(projectFolder2, "soft", "jdk1.8.zip");

                    // 确保文件存在
                    if (File.Exists(jdkInstallerPath))
                    {
                        string jdkExtractPath = Path.Combine(deployPath, "jdk8"); // 解压到项目根目录下的 soft/jdk8 文件夹
                        ExtractFile(jdkInstallerPath, jdkExtractPath); // 解压 JDK 安装包
                        string actualJdkFatherFolder = Directory.GetDirectories(jdkExtractPath)[0];
                        ConfigureEnvironmentVariables(actualJdkFatherFolder);
                    }
                }

                #region mysql远程下载 TTP
                //if (deployOption == "MySQL")
                //{
                //    Log("开始部署 MySQL...");

                //    await Task.Run(() => DownloadFile());
                //    //DownloadFile();

                //    //string mysqlExtractPath = Path.Combine(deployPath, "MySQL");
                //    //ExtractFile(Path.Combine(deployPath, "mysql.zip"), mysqlExtractPath);
                //    //string actualMysqlFolder = Directory.GetDirectories(mysqlExtractPath)[0];
                //    string installerPath = Path.Combine(
                //        deployPath,
                //        "mysql-installer-community-8.0.36.0.msi"
                //    );
                //    Log($"启动 MySQL 安装程序: {installerPath}");
                //    try
                //    {
                //        Process process = new Process();
                //        process.StartInfo.FileName = installerPath;
                //        process.StartInfo.UseShellExecute = true; // 启动安装程序
                //        process.StartInfo.CreateNoWindow = false; // 显示窗口
                //        process.Start();

                //        Log("MySQL 安装程序已启动，请手动完成安装...");
                //    }
                //    catch (Exception ex)
                //    {
                //        Log($"启动 MySQL 安装程序失败: {ex.Message}");
                //    }
                //}
                #endregion

                if (deployOption == "MySQL")
                {
                    Log("开始部署 MySQL...");
                    string projectFolder = Path.GetFullPath(
                        Path.Combine(AppDomain.CurrentDomain.BaseDirectory)
                    ); // 获取根目录路径
                    string installerPath = Path.Combine(
                        projectFolder,
                        "soft",
                        "mysql-installer-community-8.0.36.0.msi"
                    ); // 项目目录下的安装包路径

                    // 确保文件存在
                    if (File.Exists(installerPath))
                    {
                        Log($"启动 MySQL 安装程序: {installerPath}");
                        try
                        {
                            Process process = new Process();
                            process.StartInfo.FileName = installerPath;
                            process.StartInfo.UseShellExecute = true; // 启动安装程序
                            process.StartInfo.CreateNoWindow = false; // 显示窗口
                            process.Start();

                            Log("MySQL 安装程序已启动，请手动完成安装...");
                        }
                        catch (Exception ex)
                        {
                            Log($"启动 MySQL 安装程序失败: {ex.Message}");
                        }
                    }
                    else
                    {
                        Log($"MySQL 安装包未找到: {installerPath}");
                    }
                }
            }
            catch (Exception ex)
            {
                Log($"部署失败: {ex.Message}");
            }
        }

        private void ConfigureEnvironmentVariables(string actualJdkFolder)
        {
            try
            {
                Log("配置环境变量...");
                // 设置 JAVA_HOME
                string javaHome = actualJdkFolder;
                Environment.SetEnvironmentVariable(
                    "JAVA_HOME",
                    actualJdkFolder,
                    EnvironmentVariableTarget.Machine
                );
                // 更新 PATH
                string path = Environment.GetEnvironmentVariable(
                    "PATH",
                    EnvironmentVariableTarget.Machine
                );
                if (!path.Contains(javaHome))
                {
                    path = $"{javaHome}\\bin;{path}";
                    Environment.SetEnvironmentVariable(
                        "PATH",
                        path,
                        EnvironmentVariableTarget.Machine
                    );
                }
                Log("环境变量配置完成，JDK8部署成功");
            }
            catch (Exception ex)
            {
                Log($"环境变量配置失败: {ex.Message}");
            }
        }

        private async Task DownloadFileFromMinio(string objectName, string destination)
        {
            try
            {
                Log($"从对象存储服务器中下载文件 {objectName}...");

                var getObjectArgs = new GetObjectArgs()
                    .WithBucket("soft") //桶名
                    .WithObject(objectName) //对象名
                    .WithFile(destination); //下载到本地路径
                await minioClient.GetObjectAsync(getObjectArgs);

                Log($"下载完成: {destination}");
            }
            catch (Exception ex)
            {
                Log($"下载失败: {ex.Message}");
            }
        }

        private void ExtractFile(string filePath, string extractPath)
        {
            try
            {
                Log($"解压 {filePath}...");
                if (filePath.EndsWith(".zip"))
                {
                    ZipFile.ExtractToDirectory(filePath, extractPath);
                }
                Log($"解压完成: {extractPath}");
            }
            catch (Exception ex)
            {
                Log($"解压失败: {ex.Message}");
            }
        }

        private void StartProcess(string filePath, string arguments)
        {
            Log($"尝试启动: {filePath}...");
            try
            {
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = filePath,
                        Arguments = arguments,
                        WorkingDirectory = Path.GetDirectoryName(filePath),
                        UseShellExecute = true, // 使用操作系统 Shell
                        CreateNoWindow = false // 如果需要显示窗口，设置为 false
                    }
                };
                process.Start();
                Log($"{filePath} 已触发启动！");
            }
            catch (Exception ex)
            {
                Log($"启动失败: {ex.Message}");
            }
        }

        private void DownloadFile()
        {
            // FTP 服务器信息
            string ftpServer = "ftp://139.196.170.188"; // FTP 服务器地址
            string ftpUsername = "kecheng"; // FTP 用户名
            string ftpPassword = "lkczy22125@"; // FTP 密码
            string remoteFilePath = "/mysql.msi"; // 服务器上的文件路径
            string localFilePath = @"D:\modsoft\soft\mysql.msi"; // 保存到本地的路径

            try
            {
                // 创建 FTP 请求
                FtpWebRequest request = (FtpWebRequest)
                    WebRequest.Create(new Uri(ftpServer + remoteFilePath));
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
                request.UsePassive = false; 

                // 获取服务器响应
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                using (Stream responseStream = response.GetResponseStream())
                using (FileStream localFileStream = new FileStream(localFilePath, FileMode.Create))
                {
                    // 获取文件总大小
                    long totalBytes = response.ContentLength;
                    long downloadedBytes = 0;
                    byte[] buffer = new byte[8192]; // 每次读取的字节数
                    int bytesRead;

                    Log("开始下载文件...");

                    // 循环读取流并写入本地文件
                    while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        localFileStream.Write(buffer, 0, bytesRead);
                        downloadedBytes += bytesRead;

                        // 计算进度百分比
                        double progress = (double)downloadedBytes / totalBytes * 100;
                        //UpdateProgressBar(progress);
                    }

                    Log("文件下载完成！");
                    Log($"状态: {response.StatusDescription}");
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (var reader = new StreamReader(ex.Response.GetResponseStream()))
                    {
                        string responseText = reader.ReadToEnd();
                        Log("Server response: " + responseText);
                    }
                }
                Log("下载过程中出现错误: " + ex.Message);
            }
        }

        private void Log(string message)
        {
            // 确保操作在 UI 线程上执行
            if (richTextBox1.InvokeRequired)
            {
                // 使用 Invoke 方法将更新操作转发到 UI 线程
                richTextBox1.Invoke(new Action(() =>
                {
                    richTextBox1.AppendText($"{DateTime.Now}: {message}{Environment.NewLine}");
                }));
            }
            else
            {
                // 如果已经在 UI 线程，直接更新控件
                richTextBox1.AppendText($"{DateTime.Now}: {message}{Environment.NewLine}");
            }
        }

        private void Log2(double progress)
        {
            richTextBox1.Text = $"{DateTime.Now}：下载进度：{progress:F2}%";
        }


        //private void UpdateProgressBar(double progress)
        //{
        //    if (progressBar1.InvokeRequired)
        //    {
        //        // 使用 Invoke 方法确保进度条在 UI 线程上更新
        //        progressBar1.Invoke(new Action(() => progressBar1.Value = (int)progress));
        //    }
        //    else
        //    {
        //        // 直接更新进度条
        //        progressBar1.Value = (int)progress;
        //    }
        //}

    }
}
